package com.wonders.hs.pd.mm.web.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wonders.hs.pd.mm.web.config.SystemConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author banglong
 * @date 2016/9/8.
 */
@Deprecated
public class GoodsCatchUtils {

  private static final Logger logger = LoggerFactory.getLogger(GoodsCatchUtils.class);

  /**
   * 执行定时任务 每隔两个小时 更新 物品信息
   */
  @Deprecated
  public static void executeBuildGoodsCatch() {

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    long time = Long.parseLong(SystemConfig.CATCH_REFRESH_TIME);
    Runnable task = GoodsCatchUtils::getGoodsToDataSet;
    executor.scheduleAtFixedRate(
            task,
            0,
            time,
            TimeUnit.MILLISECONDS);
  }

  @Deprecated
  public static void getGoodsToDataSet() {
    logger.info("----- start send post -----");
    String url = SystemConfig.API_ADDRESS + "GoodsManager/GetGoodsToDataSet";
    Map<String, Object> params = new HashMap();
    Map<String, Object> condition = new HashMap<>();
    condition.put("Value", true);
    condition.put("Type", "Boolean");
    condition.put("FullString", null);
    condition.put("Oper", "Equal");
    condition.put("ColumnName", "IsValid");

    try {
      params.put("condition", new ObjectMapper().writeValueAsString(condition));
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }
    String result = HttpRequestUtils.sendPost(url, params);  // 发送登录请求
    logger.info("----- end send post -----");
    buildGoodsInfoJsonFIle(result);
  }

  /**
   * 创建 物品 的 json文件信息
   * 同步方法
   */
  @Deprecated
  public static synchronized void buildGoodsInfoJsonFIle(String json) {
    logger.info("----- start input json catch -----");
    // 获取路径 但是看不懂了。。
    URL url = ApplicationContextUtil.getApplicationContext().getClassLoader().getResource("");
    String urlPath = url == null ? "" : url.getFile();
    if (urlPath.contains("file")) {
      String[] arr = urlPath.split("file");
      urlPath = arr[1].substring(1, arr[1].length());
    }
    String path = urlPath.substring(1, urlPath.length()) + "static" + File.separator + "catch";
    logger.info("catch path: " + path);
    File file = new File(path);

    if (!file.exists()) {
      try {
        if (file.createNewFile()) {
          logger.info("create catch file false");
        } else {
          logger.error("create catch file success");
        }
      } catch (IOException e) {
        logger.error(e.getMessage());
      }
    }

    // 首先创建 copy 副本
    File goodsJsonCopyFile = new File(file.getPath() + File.separator + "GetGoodsToDataSet_Copy.json");
    if (!goodsJsonCopyFile.exists()) {
      try {
        if (goodsJsonCopyFile.createNewFile()) {
          logger.info("create catch file success! " + goodsJsonCopyFile.getName());
        } else {
          logger.error("create catch file false! " + goodsJsonCopyFile.getName());
        }
      } catch (IOException e) {
        logger.error(e.getMessage());
      }
    }

    BufferedWriter writer = null;
    try {
      FileOutputStream fileOutputStream = new FileOutputStream(goodsJsonCopyFile);
      writer = new BufferedWriter(new OutputStreamWriter(fileOutputStream, "UTF-8"));
      writer.write(json);
    } catch (IOException e) {
      logger.error(e.getMessage());
    } finally {
      if (writer != null) {
        try {
          writer.flush();
          writer.close();
        } catch (IOException e) {
          logger.error(e.getMessage());
        }
      }
    }

    File goodsJsonFile = new File(file.getPath() + File.separator + "GetGoodsToDataSet.json");
    if (goodsJsonFile.delete()) {
      logger.info("delete file success! " + goodsJsonFile.getName());
    }
    if (goodsJsonCopyFile.renameTo(goodsJsonFile)) {
      logger.info("catch file replace success! " + goodsJsonFile.getName());
    } else {
      logger.info("catch file replace false! " + goodsJsonFile.getName());
    }
    logger.info("----- end input json catch -----");
  }
}
